package cn.hallele.leinsteining.ms.infrastructure.plugin.captcha.client;

import cn.hallele.leinsteining.ms.infrastructure.plugin.captcha.properties.CaptchaProperties;
import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.generator.CodeGenerator;
import lombok.extern.slf4j.Slf4j;

import java.awt.*;

/**
 * CaptchaClient
 *
 * @author anle5
 * @since 2024/5/27 23:18
 */
@Slf4j
public class CaptchaClient {
    private final CaptchaProperties properties;

    private final CodeGenerator codeGenerator;

    public CaptchaClient(CodeGenerator codeGenerator, CaptchaProperties properties) {
        this.properties = properties;
        this.codeGenerator = codeGenerator;
    }

    /**
     * 生存验证码
     *
     * @return Captcha对象
     */
    public AbstractCaptcha createCaptcha() {
        AbstractCaptcha captcha = switch (this.properties.getStyle()) {
            case CIRCLE -> CaptchaUtil.createCircleCaptcha(
                    this.properties.getWidth(), this.properties.getHeight(),
                    this.properties.getCode().getLength(), this.properties.getInterfereCount());
            case GIF -> CaptchaUtil.createGifCaptcha(
                    this.properties.getWidth(),
                    this.properties.getHeight(),
                    this.properties.getCode().getLength());
            case LINE -> CaptchaUtil.createLineCaptcha(
                    this.properties.getWidth(), this.properties.getHeight(),
                    this.properties.getCode().getLength(), this.properties.getInterfereCount());
            case SHEAR -> CaptchaUtil.createShearCaptcha(
                    this.properties.getWidth(), this.properties.getHeight(),
                    this.properties.getCode().getLength(), this.properties.getInterfereCount());
        };

        CaptchaProperties.FontProperties font = properties.getFont();
        captcha.setFont(new Font(font.getName(), Font.BOLD, font.getSize()));
        captcha.setTextAlpha(this.properties.getTextAlpha());
        captcha.setGenerator(this.codeGenerator);
        return captcha;
    }

    public long getExpireSeconds() {
        return this.properties.getExpireSeconds();
    }

    public boolean verifyCaptcha(String captchaCode, String captchaCodeInCache) {
        return this.codeGenerator.verify(captchaCodeInCache, captchaCode);
    }
}
